﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace Kyoh.App.Renamer
{
    //HACK:http://dobon.net/vb/dotnet/control/tsrenderer.html
    class ToolStripToggleButton : ToolStripButton
    {
        ToolStripRenderer _renderer;
        protected override void OnOwnerChanged(EventArgs e)
        {
            if (_renderer != null)
            {
                try { _renderer.RenderItemImage -= OnRenderItemImage; }
                catch { }
                try { _renderer.RenderButtonBackground -= OnRenderButtonBackground; }
                catch { }
            }
            if (Owner != null)
            {
                _renderer = Owner.Renderer;
                if (_renderer != null)
                {
                    _renderer.RenderItemImage += OnRenderItemImage;
                    _renderer.RenderButtonBackground += OnRenderButtonBackground;
                }
            }
            base.OnOwnerChanged(e);
        }

        private void OnRenderButtonBackground(object sender, ToolStripItemRenderEventArgs e)
        {
            if (e.Item == this
                && (CheckState == System.Windows.Forms.CheckState.Indeterminate
                    || CheckState == System.Windows.Forms.CheckState.Checked))
            {
                using (Brush brush = new SolidBrush(Color.FromArgb(80, SystemColors.MenuHighlight)))
                    e.Graphics.FillRectangle(brush, e.Graphics.ClipBounds);
            }
        }

        private void OnRenderItemImage(object sender, ToolStripItemImageRenderEventArgs e)
        {
            if (e.Item == this
                && (CheckState == System.Windows.Forms.CheckState.Indeterminate
                    || CheckState == System.Windows.Forms.CheckState.Unchecked))
                ControlPaint.DrawImageDisabled(e.Graphics, e.Image, e.ImageRectangle.X, e.ImageRectangle.Y, e.Item.BackColor);
        }
    }
}
